package com.example.aihub.service.impl;

import com.example.aihub.entity.Follow;
import com.example.aihub.entity.User;
import com.example.aihub.repository.FollowRepository;
import com.example.aihub.repository.PostRepository;
import com.example.aihub.repository.UserRepository;
import com.example.aihub.service.UserService;
import com.example.aihub.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现类
 * 处理用户的注册、查询、更新等操作
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final PostRepository postRepository;
    private final FollowRepository followRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder,
                         PostRepository postRepository, FollowRepository followRepository) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.postRepository = postRepository;
        this.followRepository = followRepository;
    }

    /**
     * 注册新用户
     * @param username 用户名
     * @param email 邮箱
     * @param password 密码
     * @return 注册后的用户
     * @throws RuntimeException 如果用户名或邮箱已存在
     */
    @Override
    public User registerUser(String username, String email, String password) {
        // 检查用户名和邮箱是否已存在
        if (existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        if (existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(passwordEncoder.encode(password)); // 加密密码

        return userRepository.save(user);
    }

    /**
     * 通过用户名查找用户
     * @param username 用户名
     * @return 用户的Optional包装
     */
    @Override
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 通过邮箱查找用户
     * @param email 邮箱
     * @return 用户的Optional包装
     */
    @Override
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    /**
     * 检查用户名是否已存在
     * @param username 用户名
     * @return 如果存在返回true，否则返回false
     */
    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    /**
     * 检查邮箱是否已存在
     * @param email 邮箱
     * @return 如果存在返回true，否则返回false
     */
    @Override
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }

    /**
     * 更新用户资料
     * @param userId 用户ID
     * @param bio 个人简介
     * @param avatar 头像路径
     * @return 更新后的用户
     */
    @Override
    public User updateUserProfile(Long userId, String bio, String avatar) {
        User user = findById(userId);
        if (bio != null) {
            user.setBio(bio);
        }
        if (avatar != null) {
            user.setAvatar(avatar);
        }
        return userRepository.save(user);
    }

    /**
     * 通过ID查找用户
     * @param userId 用户ID
     * @return 用户
     * @throws ResourceNotFoundException 如果用户不存在
     */
    @Override
    public User findById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + userId));
    }

    /**
     * 获取所有用户
     * @return 用户列表
     */
    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * 获取用户发布的帖子数量
     * @param user 用户对象
     * @return 帖子数量
     */
    @Override
    public int getPostCountByUser(User user) {
        return postRepository.findByUser(user).size();
    }

    /**
     * 获取用户的粉丝数量
     * @param user 用户对象
     * @return 粉丝数量
     */
    @Override
    public int getFollowerCountByUser(User user) {
        return followRepository.countByFollowed(user);
    }

    /**
     * 获取用户关注的人数
     * @param user 用户对象
     * @return 关注人数
     */
    @Override
    public int getFollowingCountByUser(User user) {
        return followRepository.countByFollower(user);
    }

    @Override
    public void followUser(User follower, User followed) {
        if (follower.getId().equals(followed.getId())) {
            throw new RuntimeException("不能关注自己");
        }
        
        if (followRepository.existsByFollowerAndFollowed(follower, followed)) {
            throw new RuntimeException("已经关注了该用户");
        }
        
        Follow follow = new Follow();
        follow.setFollower(follower);
        follow.setFollowed(followed);
        followRepository.save(follow);
    }

    @Override
    public void unfollowUser(User follower, User followed) {
        Follow follow = followRepository.findByFollowerAndFollowed(follower, followed)
                .orElseThrow(() -> new RuntimeException("没有关注该用户"));
        followRepository.delete(follow);
    }

    @Override
    public boolean isFollowing(User follower, User followed) {
        return followRepository.existsByFollowerAndFollowed(follower, followed);
    }

    // 在UserServiceImpl类中实现updateUser方法
    @Override
    public User updateUser(User user) {
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }
}